package com.wlp.pengpicturebackend.manager.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.wlp.pengpicturebackend.config.CosClientConfig;
import com.wlp.pengpicturebackend.exception.BusinessException;
import com.wlp.pengpicturebackend.exception.ErrorCode;
import com.wlp.pengpicturebackend.exception.ThrowUtils;
import com.wlp.pengpicturebackend.manager.CosManager;
import com.wlp.pengpicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;

/**
 * 图片上传模板
 *
 * @author wlp
 * @date 2025/01/09 17:02
 **/
@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 处理输入源并生成本地临时文件
     */
    protected abstract void processFile(Object inputSource, File file) throws Exception;

    /**
     * 获取输入源的原始文件名
     */
    protected abstract String getOriginalFilename(Object inputSource);

    /**
     * 校验输入源的原始文件名
     */
    protected abstract void ValidPicture(Object inputSource);

    /**
     * 上传图片
     *
     * @param inputSource:
     * @param uploadPathPrefix:
     * @Author: wlp
     * @Date: 2025/1/9 17:17
     * @return: com.wlp.pengpicturebackend.model.dto.file.UploadPictureResult
     **/
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        //1.校验图片
        ValidPicture(inputSource);
        //2.图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originalFilename = getOriginalFilename(inputSource);
        //自己拼接文件上传路径，而不是使用原始文件，可以增强安全性
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),
                uuid, FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        //解析并返回
        File file = null;
        try {
            //3.创建临时上传文件，获取文件到服务器
            file = File.createTempFile(uploadPath, null);
            //处理文件来源
            processFile(inputSource, file);
            //4.上传到对象存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            //5.获取图片信息对象，封装对象返回结果
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            return buildResult(originalFilename, file, uploadPath, imageInfo);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            //临时文件清理
            this.deleteTempFile(file);
        }
    }

    /**
     * 封装返回结果
     *
     * @param imageInfo:
     * @param uploadPath:
     * @param originalFilename:
     * @param file:
     * @Author: wlp
     * @Date: 2025/1/14 9:50
     * @return: com.wlp.pengpicturebackend.model.dto.file.UploadPictureResult
     **/
    private UploadPictureResult buildResult(String originalFilename, File file, String uploadPath, ImageInfo imageInfo) {
        //计算宽高
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

        //封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());

        //返回可以访问的地址
        return uploadPictureResult;
    }

    /**
     * 删除临时文件
     *
     * @param file:
     * @Author: wlp
     * @Date: 2025/1/9 17:38
     * @return: void
     **/
    private void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        //删除临时文件
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }

    //todo 新增的方法
    public void validFileSize(long fileSize) {
        final long ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(fileSize > 3 * ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过3M");
    }
}
